package shun.demo.sensor;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import shun.demo.utils.UIUtil;

/**
 * Created by chen on 14-3-28.
 */
public class MonitorView extends View {

    private int mFrequency;
    private float[] mPoints;
    private int mStep = UIUtil.dipToPixel(5.0f);
    private Paint mPaint;

    public MonitorView(Context context) {
        super(context);
        init();
    }

    public MonitorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MonitorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mFrequency = 10;
        mPaint = new Paint();
        mPaint.setColor(0xffffffff);
        mPaint.setAntiAlias(false);
        mPaint.setTextSize(13);
    }

    public void monitor(float t) {
        if (mPoints == null) {
            return;
        }

        shift(false);
        mPoints[mPoints.length  - 1] = -t;
    }

    public void setFrequency(int frequency) {
        mFrequency = frequency;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w > 0) {
            // TODO: reuse the array if the length of new array less than the new one
            // TODO: copy the old data to new one if it need to extend the array
            mPoints = new float[w*2];
            for (int i = 0; i < mPoints.length; i += 2) {
                mPoints[i] = i / 2;
                mPoints[i+1] = 0;
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mPoints != null) {
            canvas.translate(0, getHeight() - 1);
            for (int i = 10; i < getHeight() - 1; i+=10) {
                canvas.drawLine(0, -i, 5, -i, mPaint);
                canvas.drawText(String.valueOf(i), 5, -i + 5, mPaint);
            }
            canvas.drawLines(mPoints, mPaint);
            canvas.drawLine(0, 0, getWidth(), 0, mPaint);
            post(mShiftRunnable);
        }
    }

    private Runnable mShiftRunnable = new Runnable() {
        @Override
        public void run() {
            shift(false);
            invalidate();
        }
    };

    private void shift(boolean clear) {
        int i = 3;
        for (; i < mPoints.length; i += 2) {
            mPoints[i-2] = mPoints[i];
        }
        if (clear) {
            mPoints[i-2] = 0;
        }
    }
}
